//
//  ViewController.m
//  FKSocketDemo
//
//  Created by 云眼科技 on 16/7/13.
//  Copyright © 2016年 CloudEyes. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncSocket.h"


@interface ViewController ()<GCDAsyncSocketDelegate>{
    GCDAsyncSocket *clientSocket;
}

@property (nonatomic, strong) NSTimer *connectTimer;
@property (nonatomic, strong) NSMutableArray <GCDAsyncSocket *> *sockets;

@end

@implementation ViewController


-(NSMutableArray<GCDAsyncSocket *> *)sockets{
    if (!_sockets) {
        _sockets = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return _sockets;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
}


- (IBAction)fk_connetBtn:(UIButton *)sender {
    
    NSError *error = nil;
    
    clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    [clientSocket connectToHost:@"192.168.3.174" onPort:8080 error:&error];
    
    if (error) {
        NSLog(@"%@", error.localizedDescription);
    }
    
}


-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    NSLog(@"连接成功");
    
    // 每隔30s像服务器发送心跳包
    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];// 在longConnectToSocket方法中进行长连接需要向服务器发送的讯息
    
    [self.connectTimer fire];
}

-(void)longConnectToSocket{
    // 根据服务器要求发送固定格式的数据，假设为指令@"longConnect"，但是一般不会是这么简单的指令
    
    NSString *longConnect = @"longConnect";
    
    NSData   *dataStream  = [longConnect dataUsingEncoding:NSUTF8StringEncoding];
    
    [clientSocket writeData:dataStream withTimeout:1 tag:1];
}



#pragma mark 断开连接
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    if (err) {
        NSLog(@"连接失败");
    }else{
        NSLog(@"正常断开");
    }
}


#pragma mark 数据发送成功
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"%s",__func__);
    
    //发送完数据手动读取，-1不设置超时
    [sock readDataWithTimeout:-1 tag:tag];
}

#pragma mark 读取数据
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSString *receiverStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%s %@",__func__,receiverStr);
}
@end













